import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Input, Select, message, DatePicker, Spin, Upload, Icon } from 'antd';

import HouseEditModal from '@/component/house/HouseEditModal';
import houseModeStyle from '@/page/house/houseMode.scss';
import houseListStyle from '@/page/house/houseList.scss';
import MModal from '@/component/common/MModal';
import moment from 'moment';
import format from '@/tool/format';
import authCheck from '@/tool/authCheck';
import ApiHelper from '@/store/ApiHelper';
import helper from '@/tool/helper';

import {  house_detail as api_house_detail,
    pull_house_into_Recycle_bin, cashbook_info, cashbook_info_update,
    cashbook_list, cashbook_add, cashbook_bill_send,
    house_his as api_house_his, house_owner_info, house_owner_info_update,
    unfreeze_rent, unfreeze_deposit, terminate_contract, stage_settlement,
    upload_picture, house_verify_add, house_lock_freeze, house_lock_unfreeze } from '@/constants/ApiTypes';

const mConfirm = MModal.confirm;
const Option = Select.Option;
import { API_URL } from '@/config';

class AuthenticationAddModal extends Component {
    static propTypes = {
        visible: PropTypes.bool,
        onClose: PropTypes.func.isRequired,
        house_no: PropTypes.string.isRequired
    };
    defaultState = {
        previewVisible: false,
        previewImage: '',
        propertyFileList: [],
        propertyImages: '',
        brokerFileList: [],
        brokerImages: '',
        shoufangFileList: [],
        shoufangImages: '',
        spinning: false
    };

    state = this.defaultState;

    componentWillReceiveProps(nextProps) {
        if (nextProps.visible) {
            this.setState(this.defaultState);
        }
    }
    handleCancel = () => this.setState({ previewVisible: false });

    handlePreview = (file) => {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true
        });
    };
    propertyHandleChange = ({ fileList }) => {
        this.handleFileUpload(fileList);
        this.setState({
            propertyFileList: fileList,
            propertyImages: this.fileChange(fileList)
        });
    };
    brokerHandleChange = ({ fileList }) => {
        this.handleFileUpload(fileList);
        this.setState({
            brokerFileList: fileList,
            brokerImages: this.fileChange(fileList)
        });
    };
    shoufangHandleChange = ({ fileList }) => {
        this.handleFileUpload(fileList);
        this.setState({
            shoufangFileList: fileList,
            shoufangImages: this.fileChange(fileList)
        });
    };
    handleFileUpload = fileList => {
        fileList.forEach((val, index) => {
            if (val.status == 'done' && val.response && !val.response.status) {
                fileList[index].status = 'error';
                MModal.success({ title: '上传失败', content: val.response.info, duration: 1.5 })
            }
        });
        return fileList;
    };
    //返回生成上传成功图片id数组
    fileChange = fileList => {
        let newFileList = [];
        fileList.forEach(val => {
            if (val.response && val.response.status) {
                newFileList.push(val.response.info[0].id);
            }
        });
        return newFileList.join(',');
    };
    submit = async () => {
        const { onClose, house_no } = this.props;
        const { propertyImages, brokerImages, shoufangImages } = this.state;
        if (propertyImages == '' && brokerImages == '' && shoufangImages == '') {
            return message.warn('请至少上传一种资料');
        }
        this.setState({ spinning: true });

        const data = {
            house_no,
            property_imgs: propertyImages, agent_imgs: brokerImages, shoufang_imgs: shoufangImages
        };

        const result = await ApiHelper.requestPost(house_verify_add, data);
        this.setState({ spinning: false });
        if (result.status) {
            MModal.success({ title: '操作成功', content: '操作成功' });
            onClose();
        } else {
            MModal.success({ title: '操作失败', content: result.info });
        }
    };
    render() {
        const { visible, onClose, house_no } = this.props;
        const { previewVisible, previewImage, propertyFileList, brokerFileList, shoufangFileList } = this.state;
        const { propertyHandleChange, brokerHandleChange, shoufangHandleChange, handlePreview, submit } = this;
        const uploadButton = (
            <div>
                <Icon type="plus" />
                <div className="ant-upload-text">上传图片</div>
            </div>
        );
        return (
            <MModal visible={visible} onClose={onClose} showMask zIndex={102} closeMaskOnClick={false} width={625} height={helper.fixHeight(570)}>
                <Spin tip="loading" spinning={this.state.spinning} delay={150}>
                    <div className={houseListStyle['house-authentication-modal']}>
                        <div className={houseListStyle['label-item']}>
                            <span className={houseListStyle['label-text']}>房产证</span>
                            <div className={houseListStyle['upload-wrap']}>
                                <Upload
                                    action={`${API_URL}/${upload_picture}`}
                                    listType="picture-card"
                                    fileList={propertyFileList}
                                    onPreview={handlePreview}
                                    onChange={propertyHandleChange}
                                    multiple
                                    accept=".jpg, .png"
                                    name="image"
                                >
                                    {uploadButton}
                                </Upload>
                            </div>
                        </div>
                        <div className={houseListStyle['label-item']}>
                            <span className={houseListStyle['label-text']}>委托书</span>
                            <div className={houseListStyle['upload-wrap']}>
                                <Upload
                                    action={`${API_URL}/${upload_picture}`}
                                    listType="picture-card"
                                    fileList={brokerFileList}
                                    onPreview={handlePreview}
                                    onChange={brokerHandleChange}
                                    accept=".jpg, .png"
                                    name="image"
                                >
                                    {uploadButton}
                                </Upload>
                            </div>
                        </div>
                        <div className={houseListStyle['label-item']}>
                            <span className={houseListStyle['label-text']}>收房合同</span>
                            <div className={houseListStyle['upload-wrap']}>
                                <Upload
                                    action={`${API_URL}/${upload_picture}`}
                                    listType="picture-card"
                                    fileList={shoufangFileList}
                                    onPreview={handlePreview}
                                    onChange={shoufangHandleChange}
                                    accept=".jpg, .png"
                                    name="image"
                                >
                                    {uploadButton}
                                </Upload>
                            </div>
                        </div>
                        <MModal visible={previewVisible} onClose={this.handleCancel} showMask width={520} height={520} zIndex={101}>
                            <div className="image-preview-modal">
                                <img alt="图片预览" src={previewImage} />
                            </div>
                        </MModal>
                        <div className={houseListStyle['modal-oper']}>
                            <a className={houseListStyle['submit-btn']} href="javascript:void(0);" onClick={submit}>提交</a>
                        </div>
                    </div>
                </Spin>
            </MModal>
        );
    }
}

class CashBookAddModal extends Component {
    constructor(props) {
        super(props);
    }
    static propTypes = {
        visible: PropTypes.bool,
        onClose: PropTypes.func.isRequired,
        type: PropTypes.oneOf(['收入', '支出']),
        houseInfo: PropTypes.object.isRequired
    };
    defaultState = {
        cashItemType: '',
        cashItemValue: '',
        date: moment()
    };
    state = this.defaultState;
    datePickerOnOk = value => {
        this.setState({ date: value });
    };
    cashItemTypeChange = e => {
        this.setState({ cashItemType: format.trim(e.target.value) });
    };
    cashItemValueChange = e => {
        this.setState({ cashItemValue: format.trim(e.target.value) });
    };
    confirmAdd = async () => {
        const { type, houseInfo } = this.props;
        const { cashItemType, cashItemValue, date } = this.state;
        if (cashItemType == '') {
            this.cashItemTypeInput.focus();
            return message.warn('请输入记录类型！', 1.5);
        }
        if (cashItemValue == '') {
            this.cashItemValueInput.focus();
            return message.warn('请输入金额！', 1.5);
        }
        const data = {
            balance_type: type == '收入' ? 1 : 2,
            item_type: cashItemType,
            item_amount: cashItemValue * 100,
            item_time: date.unix(),
            house_no: houseInfo.house_no,
            contract_no: houseInfo.contract_info.contract_no
        };
        const result = await ApiHelper.requestPost(cashbook_add, data);
        if (result.status) {
            MModal.success({ title: '操作成功', content: '添加成功', duration: 1.5 });
            this.props.onClose(true);
        } else {
            MModal.success({ title: '操作失败', content: result.info, zIndex: 103 });
        }
    };
    componentWillReceiveProps(nextProps) {
        if (nextProps.visible) {
            this.setState(this.defaultState);
        }
    }
    render() {
        const { visible, onClose, type } = this.props;
        const { date, cashItemType, cashItemValue } = this.state;
        return (
            <MModal visible={visible} onClose={onClose} width={300} height={200} showMask closeMaskOnClick={false} zIndex={102}>
                <div className={houseModeStyle['cash-book-add-modal']}>
                    <h1>添加{type}记录</h1>
                    <div className={houseModeStyle['cash-book-add-modal-item']}>
                        <span className={houseModeStyle['label-text']}>记录类型:</span>
                        <Input ref={input => this.cashItemTypeInput = input} value={cashItemType} onChange={this.cashItemTypeChange} />
                    </div>
                    <div className={houseModeStyle['cash-book-add-modal-item']}>
                        <span className={houseModeStyle['label-text']}>时间:</span>
                        <DatePicker
                            showTime
                            format="YYYY-MM-DD HH:mm:ss"
                            placeholder="选择时间"
                            onChange={() => { }}
                            onOk={this.datePickerOnOk}
                            value={date}
                        />
                    </div>
                    <div className={houseModeStyle['cash-book-add-modal-item']}>
                        <span className={houseModeStyle['label-text']}>金额:</span>
                        <Input ref={input => this.cashItemValueInput = input} value={cashItemValue} onChange={this.cashItemValueChange} />
                    </div>
                    <div className={houseModeStyle['cash-book-add-modal-item']} style={{ textAlign: 'right' }}>
                        <a className={houseModeStyle['btn-cancel']} href="javascript:void(0);" onClick={() => onClose()}>取消</a>
                        <a className={houseModeStyle['btn-confirm']} href="javascript:void(0);" onClick={this.confirmAdd}>添加</a>
                    </div>
                </div>
            </MModal>
        );
    }
}

class CashBookTable extends Component {
    static propTypes = {
        type: PropTypes.string.isRequired,
        style: PropTypes.object,
        showAddModal: PropTypes.func,
        dataSource: PropTypes.array.isRequired
    };
    showAddModal = () => {
        if (typeof this.props.showAddModal === 'function') this.props.showAddModal();
    };
    render() {
        const { type, style, dataSource } = this.props;
        const operBtn = type == 'gain' ?
            <div className={houseModeStyle['list-oper']}>
                <span className={houseModeStyle['label-gain']}>收入</span>
                <a className={houseModeStyle['btn-plus']} href="javascript:void(0);" onClick={this.showAddModal} />
            </div> :
            <div className={houseModeStyle['list-oper']}>
                <span className={houseModeStyle['label-pay']}>支出</span>
                <a className={houseModeStyle['btn-plus']} href="javascript:void(0);" onClick={this.showAddModal} />
            </div>;
        let list = dataSource.map((val, index) => {
            return (
                <tr key={index}>
                    <td>{val.item_type}</td>
                    <td>{format.timeString(val.item_time)}</td>
                    <td>{type == 'gain' ? '+' : '-'}{val.item_amount / 100}</td>
                </tr>
            );
        });
        if (list.length == 0) {
            list = <tr colSpan="3" align="middle"><td>暂无任何数据</td></tr>;
        }
        return (
            <div className={houseModeStyle['cash-book-list']} style={style}>
                {operBtn}
                <div className={houseModeStyle['list-content']}>
                    <div className={houseModeStyle['list-content-table-head']}>
                        <table cellSpacing="0" cellPadding="0" border="0">
                            <thead>
                                <tr>
                                    <th width="100">类型</th>
                                    <th width="170">时间</th>
                                    <th>金额</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                    <div className={houseModeStyle['list-content-table-body']}>
                        <table>
                            <colgroup>
                                <col style={{ width: 100 }} />
                                <col style={{ width: 170 }} />
                                <col />
                            </colgroup>
                            <tbody>
                                {list}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        );
    }
}

class CashBookSendModal extends Component {
    constructor(props) {
        super(props);
    }
    static propTypes = {
        visible: PropTypes.bool,
        onClose: PropTypes.func.isRequired,
        houseInfo: PropTypes.object.isRequired
    };
    defaultState = {
        name: '',
        amount: ''
    };
    state = this.defaultState;
    componentWillReceiveProps(nextProps) {
        if (nextProps.visible) {
            this.setState(this.defaultState);
        }
    }
    onChange = e => {
        if (e.target.name == 'gather_name') {
            this.setState({ name: format.trim(e.target.value) });
        }
        if (e.target.name == 'gather_amount') {
            this.setState({ amount: format.price(e.target.value) });
        }
    };
    send = async () => {
        const { houseInfo } = this.props;
        const { name, amount } = this.state;
        if (name == '') {
            this.name_input.focus();
            return message.warn('请输入收款名称！', 1.5);
        }
        if (amount <= 0) {
            this.amount_input.refs.input.select();
            return message.warn('收款金额必须大于0！', 1.5);
        }

        const data = {
            house_no: houseInfo.house_no,
            contract_no: houseInfo.contract_info.contract_no,
            bill_name: name,
            bill_amount: amount * 100
        };

        const result = await ApiHelper.requestPost(cashbook_bill_send, data);
        if (result.status) {
            MModal.success({ title: '操作成功', content: '已发送成功', zIndex: 103 });
            this.props.onClose();
        } else {
            MModal.success({ title: '操作失败', content: result.info, zIndex: 103 });
        }
    };
    render() {
        const { visible, onClose } = this.props;
        const { name, amount } = this.state;
        const { onChange, send } = this;
        return (
            <MModal visible={visible} onClose={onClose} width={480} height={150} showMask closeMaskOnClick={false} zIndex={102}>
                <div className={houseModeStyle['cash-book-send-modal']}>
                    <span className={houseModeStyle['label-text']}>收款：</span>
                    <div className={houseModeStyle['input-group']}>
                        <span>收款名称</span>
                        <Input ref={input => this.name_input = input} name="gather_name" value={name} onChange={onChange} />
                        <span>收款金额(元)</span>
                        <Input ref={input => this.amount_input = input} name="gather_amount" value={amount} onChange={onChange} />
                    </div>
                    <a className={houseModeStyle['cash-book-send-modal-btn']}
                        onClick={send} href="javascript:void(0);">发送</a>
                </div>
            </MModal>
        );
    }
}

class CashBookModal extends Component {
    static propTypes = {
        visible: PropTypes.bool,
        onClose: PropTypes.func.isRequired,
        houseInfo: PropTypes.object.isRequired
    };
    defaultState = {
        gatherType: 0,
        cashBookAddModalVisible: false,
        cashBookAddModalType: '收入',
        cashBookSendModalVisible: false,
        vacancyDay: 0,
        profit: 0,
        spinning: true,
        refreshHouseInfo: false,
        cashbookList: {
            in: [],
            out: []
        }
    };
    constructor(props) {
        super(props);
    }
    state = this.defaultState;
    changeGatherType = e => {
        if (e.target.name == 'gather_type_fact') {
            this.setState({ gatherType: 0 });
        } else {
            this.setState({ gatherType: 5 });
        }
    };
    closeCashBookAddModal = async refresh => {
        this.setState({ cashBookAddModalVisible: false });
        if (refresh) {
            this.setState({ spinning: true });
            let result = await this.getCashbookList(this.props);
            if (!result.status) return;
            const cashbookList = result.info;
            //重新计算利润
            await this.calcProfit(false);
            this.setState({
                cashbookList,
                spinning: false
            });
        }
    };
    showCashBookAddModal = cashBookAddModalType => {
        this.setState({ cashBookAddModalVisible: true, cashBookAddModalType });
    };
    closeBookSendModal = () => {
        this.setState({ cashBookSendModalVisible: false });
    };
    showBookSendModal = () => {
        this.setState({ cashBookSendModalVisible: true });
    };
    vacancyDayInputChange = e => {
        this.setState({ vacancyDay: format.integer(e.target.value) });
    };
    getCashbookInfo = props => {
        const { houseInfo } = props;
        const data = { house_no: houseInfo.house_no, contract_no: houseInfo.contract_info.contract_no };
        return ApiHelper.requestPost(cashbook_info, data);
    };
    getCashbookList = props => {
        const { houseInfo } = props;
        const data = { house_no: houseInfo.house_no, contract_no: houseInfo.contract_info.contract_no };
        return  ApiHelper.requestPost(cashbook_list, data);
    };
    selectCalcType = value => {
        this.setState({ gatherType: value });
    };
    async componentWillReceiveProps(nextProps) {
        if (nextProps.visible) {
            this.setState({ ...this.defaultState, spinning: true });
            const result = await this.getCashbookInfo(nextProps);
            if (!result.status) return;
            const cashbookInfo = result.info;
            const result2 = await this.getCashbookList(nextProps);
            if (!result2.status) return;
            if (result2.status) {
                this.setState({
                    gatherType: cashbookInfo.cashbook_info.calc_type,
                    vacancyDay: cashbookInfo.cashbook_info.vacancy_day,
                    profit: cashbookInfo.profit,
                    cashbookList: result2.info,
                    spinning: false
                });
            }
        }
    }
    calcProfit = async (msg = true) => {
        this.setState({ spinning: true });
        const { houseInfo } = this.props;
        const { gatherType, vacancyDay } = this.state;
        const data = {
            house_no: houseInfo.house_no,
            contract_no: houseInfo.contract_info.contract_no,
            calc_type: parseInt(gatherType),
            vacancy_day: vacancyDay
        };
        const result = await ApiHelper.requestPost(cashbook_info_update, data);
        if (!result.status) return;
        const result2 = await this.getCashbookInfo(this.props);
        const info = result2.info;
        if (result2.status) {
            this.setState({
                gatherType: info.cashbook_info.calc_type,
                vacancyDay: info.cashbook_info.vacancy_day,
                profit: info.profit,
                spinning: false,
                refreshHouseInfo: true
            });
            if (msg) MModal.success({ title: '操作提示', content: '计算成功', duration: .5 });
        }
    };
    render() {
        const { visible, onClose, houseInfo } = this.props;
        const { gatherType, cashBookAddModalVisible, cashBookAddModalType, cashBookSendModalVisible,
            vacancyDay, profit, cashbookList, refreshHouseInfo } = this.state;
        const { changeGatherType, showCashBookAddModal, closeCashBookAddModal,
            showBookSendModal, closeBookSendModal, vacancyDayInputChange, selectCalcType, calcProfit } = this;
        return (
            <MModal visible={visible} onClose={() => onClose(refreshHouseInfo)} width={1000} height={660} showMask closeMaskOnClick={false} zIndex={101}>
                <Spin tip="loading" spinning={this.state.spinning} delay={150}>
                    <div className={houseModeStyle['cash-book-modal']}>
                        <div className={houseModeStyle['cash-head']}>
                            <span>{houseInfo.address_detail}</span><em>空置期<span>{vacancyDay}天</span></em>
                        </div>
                        <div className={houseModeStyle['cash-book-list-group']}>
                            <CashBookTable type="gain" style={{ paddingRight: 25 }} dataSource={cashbookList.in} showAddModal={() => { showCashBookAddModal('收入') }} />
                            <CashBookTable type="pay" style={{ paddingLeft: 25 }} dataSource={cashbookList.out} showAddModal={() => { showCashBookAddModal('支出') }} />
                            <CashBookAddModal visible={cashBookAddModalVisible} houseInfo={houseInfo} onClose={closeCashBookAddModal} type={cashBookAddModalType} />
                        </div>
                        <div className={houseModeStyle['cash-book-gather']}>
                            <div className={houseModeStyle['gather-profit']}>
                                <span className={houseModeStyle['label-text']}>利润</span><span>{isNaN(profit) ? profit : (profit / 100 + '元')}</span>
                            </div>
                            <div className={houseModeStyle['gather-oper']}>
                                <div className={houseModeStyle['gather-oper-item']}>
                                    空置期
                                    <span className={houseModeStyle['gather-oper-input']}><Input value={vacancyDay} onChange={vacancyDayInputChange} />天</span>
                                </div>
                                <div className={houseModeStyle['gather-oper-item']}>
                                    <span>按实际付款结算</span>
                                    <a name="gather_type_fact"
                                        onClick={changeGatherType}
                                        className={`${houseModeStyle['check-btn']}${gatherType == 0 ? ' ' + houseModeStyle['selected'] : ''}`} href="javascript:void(0);" />
                                </div>
                                <div className={houseModeStyle['gather-oper-item']}>
                                    <span>按
                                        {gatherType > 0 ?
                                            <Select defaultValue="5" value={`${gatherType}`} style={{ width: 80 }} onChange={selectCalcType}>
                                                <Option value="5">全部</Option>
                                                <Option value="1">月</Option>
                                                <Option value="2">季</Option>
                                                <Option value="3">半年</Option>
                                                <Option value="4">年</Option>
                                            </Select> :
                                            <Select disabled defaultValue="5" style={{ width: 80 }}>
                                                <Option value="5">全部</Option>
                                                <Option value="1">月</Option>
                                                <Option value="2">季</Option>
                                                <Option value="3">半年</Option>
                                                <Option value="4">年</Option>
                                            </Select>}
                                        结算
                                    </span>
                                    <a name="gather_type_select"
                                        onClick={this.changeGatherType}
                                        className={`${houseModeStyle['check-btn']}${gatherType != 0 ? ' ' + houseModeStyle['selected'] : ''}`} href="javascript:void(0);" />
                                </div>
                            </div>
                            <div className={houseModeStyle['calc-btn']}>
                                <a href="javascript:void(0);" onClick={calcProfit}>计算</a>
                            </div>
                            <div className={houseModeStyle['gather-btn']}>
                                <a href="javascript:void(0);" onClick={showBookSendModal}>收款</a>
                                <CashBookSendModal visible={cashBookSendModalVisible} houseInfo={houseInfo} onClose={closeBookSendModal} />
                            </div>
                        </div>
                        {houseInfo.renter_info &&
                        <div className={houseModeStyle['cash-book-rent-info']}>
                            <span className={houseModeStyle['label-text']}>租客：{houseInfo.renter_info.renter_name}</span>
                            <span className={houseModeStyle['label-text']}>电话：{houseInfo.renter_info.mobile}</span>
                            <span className={houseModeStyle['label-text']}>租期：{houseInfo.renter_info.rent_time}</span>
                        </div>}
                    </div>
                </Spin>
            </MModal>
        );
    }
}

class EditLabel extends Component {
    static propTypes = {
        label: PropTypes.string.isRequired,
        inputWidth: PropTypes.number,
        value: PropTypes.oneOfType([
            PropTypes.string,
            PropTypes.number
        ]),
        onChange: PropTypes.func,
        onPreChange: PropTypes.func,
        placeholder: PropTypes.string,
        style: PropTypes.object,
        postfix: PropTypes.string,
        name: PropTypes.string,
        closeEditMode: PropTypes.bool,
        editMode: PropTypes.bool
    };
    state = {
        editMode: false,
        _value: ''
    };
    componentDidMount() {
        this.setState({ _value: this.props.value ? this.props.value : '' });
    }
    componentWillReceiveProps(nextProps) {
        if (nextProps.closeEditMode) this.cancelEdit(nextProps);
        if (nextProps.editMode) {
            this.startEdit();
        } else {
            this.cancelEdit(nextProps);
        }
    }
    startEdit = () => {
        this.setState({ editMode: true });
        setTimeout(() => {
            const el = this.input;
            let range;
            if (el.setSelectionRange) {
                el.focus();
                el.setSelectionRange(el.value.length, el.value.length)
            } else {
                range = el.createTextRange();
                range.collapse(false);
                range.select();
            }
        });
    };
    saveEdit = () => {
        this.setState({ editMode: false });
        if (this.props.onChange) this.props.onChange({ value: this.state._value, name: this.props.name });
    };
    cancelEdit = (props = this.props) => {
        this.setState({
            _value: props.value ? props.value : '',
            editMode: false
        });
    };
    onChange = e => {
        this.setState({ _value: e.target.value });
        if (this.props.onPreChange) this.props.onPreChange({ value: e.target.value, name: this.props.name });
    };
    onEnter = e => {
        if (e.keyCode == 13) this.saveEdit();
        if (e.keyCode == 27) this.cancelEdit();
    };
    render() {
        const { editMode, _value } = this.state;
        const { label, placeholder, style, postfix, inputWidth } = this.props;
        let inputStyle = {};
        if (inputWidth > 0) inputStyle.width = inputWidth;
        if (editMode) {
            return (
                <p className={houseModeStyle['owner-label-text']} style={style}>
                    <span>{label}：<input ref={input => this.input = input} style={inputStyle} value={_value} placeholder={placeholder} onChange={this.onChange} onKeyDown={this.onEnter} /></span>
                    <a className={houseModeStyle['label-text-edit']} href="javascript:void(0);" onClick={this.saveEdit}>确定</a><a className={houseModeStyle['label-text-edit']} href="javascript:void(0);" onClick={this.cancelEdit}>取消</a>
                </p>
            );
        } else {
            return (
                <p className={houseModeStyle['owner-label-text']} style={style}>
                    <span>{label}：{_value}{postfix}</span>
                    <a className={houseModeStyle['label-text-edit']} href="javascript:void(0);" onClick={this.startEdit}>修改</a>
                </p>
            );
        }
    }
}

class HouseOwnerModal extends Component {
    constructor(props) {
        super(props);
    }
    static propTypes = {
        visible: PropTypes.bool,
        onClose: PropTypes.func.isRequired,
        houseInfo: PropTypes.object.isRequired
    };
    defaultState = {
        spinning: true,
        editModeAll: false,
        ownerInfoUpdate: {
            owner: '',
            rent: '',
            rent_time: '',
            mobile: '',
            pay_type: '',
            vacancy_day: '',
            used_vacancy_day: '',
            inc: false
        }
    };
    preInfo = {
        owner: '',
        rent: '',
        rent_time: '',
        mobile: '',
        pay_type: '',
        vacancy_day: '',
        used_vacancy_day: ''
    };
    state = this.defaultState;
    saveOwnerInfo = async owner_info => {
        if (owner_info.rent != '') {
            let _rentArray = `${owner_info.rent}`.split('-');
            for (let i = 0; i < _rentArray.length; i++) {
                if (isNaN(_rentArray[i])) return MModal.success({ title: '错误提示', content: '必须用-分割递增房租' });
                _rentArray[i] = _rentArray[i] * 100;
            }
            owner_info.rent = _rentArray.join('-');
        }
        const data = {
            house_no: this.props.houseInfo.house_no,
            owner_info: JSON.stringify(owner_info)
        };
        const result = await ApiHelper.requestPost(house_owner_info_update, data);
        if (result.status) {
            MModal.success({ title: '操作成功', content: '保存成功', duration: 1.5 });
            this.props.onClose(true);
        } else {
            MModal.success({ title: '操作失败', content: result.info });
        }
    };
    saveOwnerInfoConfirm = () => {
        let confirm = false;
        let owner_info = { ...this.state.ownerInfoUpdate };
        let pre_info = this.preInfo;
        for (let p in pre_info) {
            if (pre_info[p] != '') {
                confirm = true;
                owner_info[p] = pre_info[p];
            }
        }
        if (confirm) {
            mConfirm({
                title: '有内容未确定保存，需要保存未确定内容吗？',
                titleStyle: { fontSize: 16 },
                width: 300,
                height: 177,
                content: '',
                okText: '是',
                cancelText: '否',
                okClassName: 'primary-btn-ok',
                cancelClassName: 'primary-btn-cancel',
                showTopClose: false,
                zIndex: 102,
                onOk: () => {
                    return this.saveOwnerInfo(owner_info);
                },
                onCancel: () => {
                    return this.saveOwnerInfo(this.state.ownerInfoUpdate);
                }
            });
        } else {
            return this.saveOwnerInfo(this.state.ownerInfoUpdate);
        }

    };
    getHouseOwnerInfo = props => {
        const { houseInfo } = props;
        const data = { house_no: houseInfo.house_no };
        return ApiHelper.requestPost(house_owner_info, data);
    };
    async componentWillReceiveProps(nextProps) {
        if (nextProps.visible) {
            this.preInfo = { ...this.defaultState.ownerInfoUpdate };
            this.setState({ ...this.defaultState, spinning: true });
            const result = await this.getHouseOwnerInfo(nextProps);
            if (result.status) {
                let ownerInfo = false;
                if (result.info !== false && result.info !== '') {
                    ownerInfo = JSON.parse(result.info);
                    const ownerInfoUpdate = {
                        owner: ownerInfo.owner !== undefined ? ownerInfo.owner : '',
                        rent: ownerInfo.rent ? `${ownerInfo.rent}`.split('-').map(val => val / 100).join('-') : '',
                        rent_time: ownerInfo.rent_time !== undefined ? ownerInfo.rent_time : '',
                        mobile: ownerInfo.mobile !== undefined ? ownerInfo.mobile : '',
                        pay_type: ownerInfo.pay_type !== undefined ? ownerInfo.pay_type : '',
                        vacancy_day: ownerInfo.vacancy_day !== undefined ? ownerInfo.vacancy_day : '',
                        used_vacancy_day: ownerInfo.used_vacancy_day !== undefined ? ownerInfo.used_vacancy_day : '',
                        inc: ownerInfo.inc !== undefined ? ownerInfo.inc : false
                    };
                    this.setState({ ownerInfoUpdate });
                }
                this.setState({ spinning: false });
            }
        }
    }
    editLabelOnchange = e => {
        if (e.name) {
            let ownerInfoUpdate = { ...this.state.ownerInfoUpdate };
            ownerInfoUpdate[e.name] = e.value;
            this.preInfo[e.name] = '';
            this.setState({ ownerInfoUpdate });
        }
    };
    editLabelOnPreChange = e => {
        if (e.name) {
            this.preInfo[e.name] = e.value;
        }
    };
    //房租是否递增
    selectRentInc = inc => {
        let ownerInfoUpdate = { ...this.state.ownerInfoUpdate };
        ownerInfoUpdate.inc = inc;
        this.setState({ ownerInfoUpdate });
    };
    startEditAll = () => {
        this.setState({ editModeAll: true });
    };
    cancelEditAll = () => {
        this.setState({ editModeAll: false });
    };
    render() {
        const { visible, onClose } = this.props;
        const { ownerInfoUpdate, editModeAll } = this.state;
        const { editLabelOnchange, editLabelOnPreChange, selectRentInc } = this;
        let { owner, rent, rent_time, mobile, pay_type, vacancy_day, used_vacancy_day, inc } = ownerInfoUpdate;
        return (
            <MModal showMask closeMaskOnClick={false} visible={visible} onClose={onClose} width={420} height={360} zIndex={101}>
                <Spin tip="loading" spinning={this.state.spinning} delay={150}>
                    {!this.state.spinning ?
                        <div className={houseModeStyle['house-owner-edit-modal']}>
                            <p className={houseModeStyle['modal-title']}>房东编辑</p>
                            <div className={houseModeStyle['modal-content']}>
                                <EditLabel name="owner" label="房东" value={owner} onChange={editLabelOnchange}
                                    editMode={editModeAll}
                                    closeEditMode={!visible} onPreChange={editLabelOnPreChange} />
                                {!inc ?
                                    <EditLabel name="rent" label="租金" value={rent} postfix="元" onChange={editLabelOnchange}
                                        editMode={editModeAll}
                                        closeEditMode={!visible} onPreChange={editLabelOnPreChange} /> :
                                    [
                                        <EditLabel key="rent-inc" name="rent" label="递增租金" value={rent} postfix="（元）" onChange={editLabelOnchange}
                                            editMode={editModeAll}
                                            closeEditMode={!visible} onPreChange={editLabelOnPreChange} />,
                                        <p key="p-tip" className={houseModeStyle['owner-label-text-tip']}>递增租金:字符-隔开,如1000-2000</p>
                                    ]}
                                <EditLabel name="rent_time" label="租期" value={rent_time} postfix="元" inputWidth={200}
                                    editMode={editModeAll}
                                    onChange={editLabelOnchange} closeEditMode={!visible} onPreChange={editLabelOnPreChange} />
                                <p className={houseModeStyle['owner-label-text-tip']}>租期:中文字符(至)隔开,如2018-01-10至2019-10-10</p>
                                <EditLabel name="mobile" label="电话" value={mobile} onChange={editLabelOnchange}
                                    editMode={editModeAll}
                                    closeEditMode={!visible} onPreChange={editLabelOnPreChange} />
                                <EditLabel name="pay_type" label="付款" value={pay_type} onChange={editLabelOnchange}
                                    editMode={editModeAll}
                                    closeEditMode={!visible} onPreChange={editLabelOnPreChange} />
                                { inc ?
                                    <p key="p-radio" className={houseModeStyle['owner-label-text']}>
                                        房租是否递增 <span className={houseModeStyle['inc-btns']}><a className={houseModeStyle['active']} href="javascript:void(0);">是</a><a href="javascript:void(0);" onClick={() => selectRentInc(false)}>否</a></span>
                                    </p> :
                                    <p className={houseModeStyle['owner-label-text']}>
                                        房租是否递增 <span className={houseModeStyle['inc-btns']}><a href="javascript:void(0);" onClick={() => selectRentInc(true)}>是</a><a className={houseModeStyle['active']} href="javascript:void(0);">否</a></span>
                                    </p> }
                                <div className={houseModeStyle['owner-label-text']}>
                                    <EditLabel name="vacancy_day" label="总空置期" value={vacancy_day} onChange={editLabelOnchange}
                                        editMode={editModeAll}
                                        postfix="天" inputWidth={35} style={{ display: 'inline' }} closeEditMode={!visible} onPreChange={editLabelOnPreChange} />
                                    <EditLabel name="used_vacancy_day" label="已用空置期" value={used_vacancy_day}
                                        editMode={editModeAll}
                                        onChange={editLabelOnchange} postfix="天" inputWidth={35} style={{ display: 'inline' }} closeEditMode={!visible} onPreChange={editLabelOnPreChange} />
                                </div>
                            </div>
                            <div className={houseModeStyle['oper-btns']}>
                                { editModeAll ?
                                    <a href="javascript:void(0);" onClick={this.cancelEditAll}>取消</a> :
                                    <a href="javascript:void(0);" onClick={this.startEditAll}>编辑</a> }
                                <a className={houseModeStyle['confirm-btn']} href="javascript:void(0);" onClick={this.saveOwnerInfoConfirm}>保存</a>
                            </div>
                        </div> :
                        <div className={houseModeStyle['house-owner-edit-modal']}/> }
                </Spin>
            </MModal>
        );
    }
}

class HouseDetailModal extends Component {
    static propTypes = {
        visible: PropTypes.bool,
        onClose: PropTypes.func.isRequired,
        houseInfo: PropTypes.object.isRequired
    };
    defaultState = {
        spinning: true,
        detailInfo: {
            owner_info: false,
            rent_his: []
        },
        authenticationAddModalVisible: false
    };
    state = this.defaultState;
    //获取房源历史
    getHouseHis = props => {
        const { houseInfo } = props;
        const data = { house_no: houseInfo.house_no };
        return ApiHelper.requestPost(api_house_his, data);
    };
    async componentWillReceiveProps(nextProps) {
        if (nextProps.visible) {
            this.setState({ ...this.defaultState, spinning: true });
            const result = await this.getHouseHis(nextProps);
            if (result.status) {
                this.setState({ detailInfo: result.info, spinning: false });
            }
        }
    }
    showAuthenticationAddModal = () => {
        this.setState({ authenticationAddModalVisible: true });
    };
    closeAuthenticationAddModal = () => {
        this.setState({ authenticationAddModalVisible: false });
    };
    render() {
        const { visible, onClose, houseInfo } = this.props;
        const { owner_info, rent_his } = this.state.detailInfo;
        const { authenticationAddModalVisible } = this.state;
        const { showAuthenticationAddModal, closeAuthenticationAddModal } = this;
        const rent_list = rent_his.map((val, index) => {
            const label_cls = isNaN(val.calcProfit) ? houseModeStyle['list-label-gain'] : (val.calcProfit > 0 ? houseModeStyle['list-label-gain'] : houseModeStyle['list-label-deficit']);
            const label_text = isNaN(val.calcProfit) ? '利润' : (val.calcProfit > 0 ? '利润' : '亏损');
            const cash_list = val.cashbook.map((item, index2) => {
                return (
                    <div key={index2} className={houseModeStyle['list-item-detail-i']}>
                        <span>{item.item_type}</span><span>{format.timeString(item.item_time)}</span><span>{item.balance_type == 1 ? '+' : '-'}{item.item_amount / 100 + '元'}</span>
                    </div>
                );
            });
            return (
                <div key={index} className={houseModeStyle['detail-info-item']}>
                    <p className={houseModeStyle['list-item-line']}>
                        <span className={houseModeStyle['list-label-text']}><b>租客：</b>{val.renter_name}</span>
                        <span className={houseModeStyle['list-label-text']}>租金：{val.rent / 100}元</span>
                        <span className={houseModeStyle['list-label-text']}>租期：{val.rent_time}</span>
                    </p>
                    <p className={houseModeStyle['list-item-line']}>
                        <span className={houseModeStyle['list-label-text']}>电话：{val.renter_mobile}</span>
                        <span className={houseModeStyle['list-label-text']}>付款：{val.pay_type}</span>
                        <span className={houseModeStyle['list-label-text']}>押金：{val.deposit / 100}元</span>
                        <span className={houseModeStyle['list-item-oper']}><span className={label_cls}>{label_text}</span><span className={houseModeStyle['list-label-text']}>{isNaN(val.calcProfit) ? val.calcProfit : (val.calcProfit / 100 + '元')}</span>
                            <a href={`${API_URL}/${val.contract_url}`} target="_blank">查看</a>/<a href={`${API_URL}/${val.contract_pdf_url}`}>下载合同</a></span>
                    </p>
                    <div className={houseModeStyle['list-item-line']}>
                        <span className={houseModeStyle['list-label-d']}>明细</span>
                        <div className={houseModeStyle['list-item-detail']}>
                            {cash_list}
                        </div>
                        <div style={{ clear: 'both' }} />
                    </div>
                </div>
            );
        });
        return (
            <MModal showMask closeMaskOnClick={false} visible={visible} onClose={onClose} width={1000} height={helper.fixHeight(650)} zIndex={101}>
                <Spin tip="loading" spinning={this.state.spinning} delay={150}>
                    <div className={houseModeStyle['house-detail-modal']}>
                        {owner_info ?
                            <div className={houseModeStyle['detail-modal-head']}>
                                <a className={houseModeStyle['detail-verify-add']} href="javascript:void(0);" onClick={showAuthenticationAddModal}>补充认证资料</a>
                                <p>{houseInfo.address_detail}</p>
                                <p>
                                    <span className={houseModeStyle['head-label-text']}>房东：{owner_info.owner}</span>
                                    <span className={houseModeStyle['head-label-text']}>租金：{!owner_info.rent ? '' : `${owner_info.rent}`.split('-').map(val => val / 100).join('-') + '元'}</span>
                                    <span className={houseModeStyle['head-label-text']}>租期：{owner_info.rent_time}</span>
                                </p>
                                <p>
                                    <span className={houseModeStyle['head-label-text']}>电话：{owner_info.mobile}</span>
                                    <span className={houseModeStyle['head-label-text']}>付款：{owner_info.pay_type}</span>
                                </p>
                            </div> :
                            <div className={houseModeStyle['detail-modal-head']}>
                                <p>{houseInfo.address_detail}</p>
                                <p>房东信息暂无</p>
                            </div>}
                        <div className={houseModeStyle['detail-info-list']}>
                            {rent_list.length > 0 ? rent_list :
                                <p style={{ textAlign: 'center' }}>合同历史暂无</p>}
                        </div>
                    </div>
                    {houseInfo.house_no &&
                    <AuthenticationAddModal visible={authenticationAddModalVisible} onClose={closeAuthenticationAddModal} house_no={houseInfo.house_no}/>}
                </Spin>
            </MModal>
        );

    }
}

class UnfreezeRenterModal extends Component {
    constructor(props) {
        super(props);
    }
    static propTypes = {
        visible: PropTypes.bool,
        onClose: PropTypes.func.isRequired
    };
    state = {
        profit: ''
    };
    onChange = e => {
        let value = e.target.value;
        if (e.target.name == 'profit') {
            this.setState({ profit: format.price(value) });
        }
    };
    confirm = async () => {
        const { profit } = this.state;
        if (profit <= 0) {
            this.profit_input.refs.input.select();
            return message.warn('收入必须大于0！', 1.5);
        }
        const data = {
            amount: profit * 100
        };
        const result = await ApiHelper.requestPost(unfreeze_rent, data);
        if (result.status) {
            MModal.success({ title: '操作成功', content: '申请成功', duration: 1.5 });
            this.props.onClose();
        } else {
            MModal.success({ title: '操作失败', content: result.info });
        }
    };
    render() {
        const { visible, onClose } = this.props;
        const { profit } = this.state;
        const { onChange, confirm } = this;
        return (
            <MModal visible={visible} onClose={onClose} width={240} height={140} showMask closeMaskOnClick={false} zIndex={101}>
                <div className={houseModeStyle['unfreeze-modal']}>
                    <h1>解冻租金</h1>
                    <div className={houseModeStyle['unfreeze-modal-item']}>
                        <span className={houseModeStyle['label-text']}>
                            收入：
                        </span>
                        <Input name="profit" ref={input => { this.profit_input = input }} value={profit} onChange={onChange} />
                    </div>
                    <div className={houseModeStyle['unfreeze-modal-item']} style={{ textAlign: 'center' }}>
                        <a className={houseModeStyle['confirm-btn']} href="javascript:void(0);" onClick={confirm}>提交申请</a>
                    </div>
                </div>
            </MModal>
        );
    }
}

class UnfreezeDepositModal extends Component {
    constructor(props) {
        super(props);
    }
    static propTypes = {
        visible: PropTypes.bool,
        onClose: PropTypes.func.isRequired
    };
    state = {
        renter_profit: '',
        profit: ''
    };
    onChange = e => {
        let value = e.target.value;
        let name = e.target.name;
        if (name == 'renter_profit') {
            this.setState({ renter_profit: format.price(value) });
        }
        if (name == 'profit') {
            this.setState({ profit: format.price(value) });
        }
    };
    confirm = async () => {
        const { renter_name, profit } = this.state;
        if (renter_name == '') {
            this.renter_profit_input.focus();
            return message.warn('请输入租客收入！', 1.5);
        }
        if (profit <= 0) {
            this.profit_input.refs.input.select();
            return message.warn('收入必须大于0！', 1.5);
        }

        const data = {
            renter_name: renter_name,
            amount: profit * 100
        };
        const result = await ApiHelper.requestPost(unfreeze_deposit, data);
        if (result.status) {
            MModal.success({ title: '操作成功', content: '申请成功', duration: 1.5 });
            this.props.onClose();
        } else {
            MModal.success({ title: '操作失败', content: result.info });
        }
    };
    render() {
        const { visible, onClose } = this.props;
        const { renter_name, profit } = this.state;
        const { onChange, confirm } = this;
        return (
            <MModal visible={visible} onClose={onClose} width={240} height={180} showMask closeMaskOnClick={false} zIndex={101}>
                <div className={houseModeStyle['unfreeze-modal']}>
                    <h1>解冻押金</h1>
                    <div className={houseModeStyle['unfreeze-modal-item']}>
                        <span className={houseModeStyle['label-text']}>
                            租客：
                        </span>
                        <Input name="renter_profit" ref={input => { this.renter_profit_input = input }} value={renter_name} onChange={onChange} />
                    </div>
                    <div className={houseModeStyle['unfreeze-modal-item']}>
                        <span className={houseModeStyle['label-text']}>
                            收入：
                        </span>
                        <Input name="profit" ref={input => { this.profit_input = input }} value={profit} onChange={onChange} />
                    </div>
                    <div className={houseModeStyle['unfreeze-modal-item']} style={{ textAlign: 'center' }}>
                        <a className={houseModeStyle['confirm-btn']} href="javascript:void(0);" onClick={confirm}>提交申请</a>
                    </div>
                </div>
            </MModal>
        );
    }
}

class HouseInfoModal extends Component {
    constructor(props) {
        super(props);
    }
    static propTypes = {
        visible: PropTypes.bool,
        onClose: PropTypes.func.isRequired,
        itemInfo: PropTypes.object.isRequired
    };
    defaultState = {
        spinning: false,
        houseInfo: {},
        detailModalVisible: false,
        ownerVisible: false,
        cashBookVisible: false,
        unfreezeDepositVisible: false,
        unfreezeRentVisible: false,
        houseEditModalVisible: false
    };
    state = this.defaultState;
    //获取房源基本信息
    getHouseInfo = props => {
        const { itemInfo } = props;
        const data = { house_no: itemInfo.house_no };
        return ApiHelper.requestPost(api_house_detail, data);
    };
    async componentWillReceiveProps(nextProps) {
        if (nextProps.visible && !this.state.spinning) {
            this.setState({ ...this.defaultState, spinning: true });
            const result = await this.getHouseInfo(nextProps);
            if (result.status) {
                this.setState({ houseInfo: result.info, spinning: false });
            }
        }
    }
    //刷新房源信息
    refreshHouseInfo = async () => {
        this.setState({ ...this.defaultState, spinning: true });
        const result = await this.getHouseInfo(this.props);
        if (result.status) {
            this.setState({ houseInfo: result.info, spinning: false });
        }
    };
    terminateContract = async () => {
        const contract_no = this.state.houseInfo.contract_info.contract_no;
        const data = { contract_no };
        const result = await ApiHelper.requestPost(terminate_contract, data);
        if (result.status) {
            MModal.success({ title: '操作成功', content: '操作成功', duration: 1.5 });
            //刷新房源信息
            this.refreshHouseInfo();
            return result.info;
        } else {
            MModal.success({ title: '操作失败', content: result.info });
        }
    };
    //支付分期合同剩余本金
    payStageAmount = async hide => {
        mConfirm({
            title: '确定要支付吗',
            titleStyle: { fontSize: 16 },
            width: 300,
            height: 177,
            content: '',
            okText: '是',
            cancelText: '否',
            okClassName: 'primary-btn-ok',
            cancelClassName: 'primary-btn-cancel',
            showTopClose: false,
            onOk: async () => {
                const data = { contract_no: this.state.houseInfo.contract_info.contract_no };
                const result = await ApiHelper.requestPost(stage_settlement, data);
                if (result.status) {
                    MModal.success({ title: '操作成功', content: '操作成功', duration: 1.5 });
                    //关闭对话框，刷新数据
                    hide();
                    this.refreshHouseInfo();
                } else {
                    MModal.success({ title: '操作失败', content: result.info });
                }
            },
            onCancel() { }
        });
    };
    //支付分期合同剩余本金
    payStageContract = pay_amount => {
        //pay_amount 待还本金
        if (pay_amount === false) return;
        mConfirm({
            title: '合同已终止',
            width: 420,
            height: 200,
            content: hide => {
                return (
                    <div>待还本金 <span style={{ marginLeft: 10, color: 'red' }}>{pay_amount / 100}元</span>
                        <a className="primary-btn-ok"
                            style={{ marginLeft: 30 }}
                            href="javascript:void(0);" onClick={() => this.payStageAmount(hide)}>去支付</a>
                    </div>
                );
            },
            contentStyle: { width: 300, height: 100 },
            showBtn: false,
            showTopClose: true,
            onOk() {},
            onCancel() { }
        });
    };
    terminateContractConfirm = () => {
        const { houseInfo } = this.state;
        const contract_info = houseInfo.contract_info;
        if (!contract_info) return MModal.success({ title: '错误提示', content: '该房源暂无合同信息', duration: 1.5 });
        let { contract_type } = contract_info;
        if (contract_type == '普通合同') {
            mConfirm({
                title: '终止合同',
                content: '合同终止后，双方合同即终止，租客将不能再支付房租。',
                contentStyle: { width: 320, height: 160 },
                okText: '终止',
                showTopClose: false,
                onOk: this.terminateContract,
                onCancel() { }
            });
        } else {
            mConfirm({
                title: '终止分期合同',
                content: () => {
                    if (contract_info.stage_will_pay) {
                        return <span dangerouslySetInnerHTML={{ __html: '分期合同终止后，双方合同即终止，租客将不能再支付房租，<br/>剩余本金（￥' + contract_info.stage_will_pay / 100  + '元）将由您立即支付。' }} />
                    } else {
                        return <span dangerouslySetInnerHTML={{ __html: '分期合同终止后，双方合同即终止，租客将不能再支付房租。' }} />
                    }
                },
                contentStyle: { width: 320, height: 160 },
                okText: '终止',
                showTopClose: false,
                onOk: async () => {
                    const info = await this.terminateContract();
                    this.payStageContract(info.pay_amount);
                },
                onCancel() { }
            });
        }

    };
    closeDetailModal = () => {
        this.setState({ detailModalVisible: false });
    };
    showDetailModal = () => {
        this.setState({ detailModalVisible: true });
    };
    closeOwnerModal = async refresh => {
        this.setState({ ownerVisible: false });
        if (refresh) {
            this.refreshHouseInfo();
        }
    };
    showOwnerModal = () => {
        this.setState({ ownerVisible: true });
    };
    closeHouseEditModal = async refresh => {
        this.setState({ houseEditModalVisible: false });
        if (refresh) {
            this.refreshHouseInfo();
        }
    };
    showHouseEditModal = () => {
        this.setState({ houseEditModalVisible: true });
    };
    closeCashBookModal = refresh => {
        if (refresh) this.refreshHouseInfo();
        this.setState({ cashBookVisible: false });
    };
    showCashBookModal = () => {
        const { houseInfo } = this.state;
        if (!houseInfo.contract_info) return MModal.success({ title: '提示', content: '暂无进行中合同', duration: 1.5 });
        this.setState({ cashBookVisible: true });
    };
    deleteHouseConfirm = () => {
        if (!this.state.houseInfo.can_delete)
            return MModal.success({ title: '错误提示', content: '空置房源才能删除！' });
        mConfirm({
            title: '是否将该房源放入回收站',
            titleStyle: { fontSize: 16 },
            width: 300,
            height: 177,
            content: '',
            okText: '是',
            cancelText: '否',
            okClassName: 'primary-btn-ok',
            cancelClassName: 'primary-btn-cancel',
            showTopClose: false,
            onOk: async () => {
                const data = { house_no: this.props.itemInfo.house_no };
                const result = await ApiHelper.requestPost(pull_house_into_Recycle_bin, data);
                if (result.status) {
                    MModal.success({ title: '操作成功', content: '操作成功', duration: 1.5 });
                    //刷新房源模式列表 //关闭当前模态框
                    this.props.onClose(true);
                } else {
                    MModal.success({ title: '操作失败', content: result.info });
                }
            },
            onCancel() { }
        });
    };
    closeUnfreezeDepositModal = () => {
        this.setState({ unfreezeDepositVisible: false });
    };
    showUnfreezeDepositModal = () => {
        if (!authCheck('资金管理', '房源')) return MModal.success({ title: '错误提示', content: '您无权进行该操作' });
        this.setState({ unfreezeDepositVisible: true });
    };
    closeUnfreezeRentModal = () => {
        this.setState({ unfreezeRentVisible: false });
    };
    showUnfreezeRentModal = () => {
        if (!authCheck('资金管理', '房源')) return MModal.success({ title: '错误提示', content: '您无权进行该操作' });
        this.setState({ unfreezeRentVisible: true });
    };
    frozenLock = () => {
        const { itemInfo } = this.props;
        const data = { house_no: itemInfo.house_no };
        mConfirm({
            title: '确定要冻结该房源智能锁吗？',
            titleStyle: { fontSize: 16 },
            width: 300,
            height: 177,
            content: '',
            okText: '是',
            cancelText: '否',
            okClassName: 'primary-btn-ok',
            cancelClassName: 'primary-btn-cancel',
            showTopClose: false,
            zIndex: 102,
            onOk: async () => {
                const result = await ApiHelper.requestPost(house_lock_freeze, data);
                if (result.status) {
                    MModal.success({ title: '操作成功', content: '冻结成功', duration: 1.5 });
                    this.refreshHouseInfo();
                } else {
                    MModal.success({ title: '操作失败', content: result.info });
                }

            },
            onCancel() {}
        });
    };
    unFrozenLock = () => {
        const { itemInfo } = this.props;
        const data = { house_no: itemInfo.house_no };
        mConfirm({
            title: '确定要解冻该房源智能锁吗？',
            titleStyle: { fontSize: 16 },
            width: 300,
            height: 177,
            content: '',
            okText: '是',
            cancelText: '否',
            okClassName: 'primary-btn-ok',
            cancelClassName: 'primary-btn-cancel',
            showTopClose: false,
            zIndex: 102,
            onOk: async () => {
                const result = await ApiHelper.requestPost(house_lock_freeze, data);
                if (result.status) {
                    MModal.success({ title: '操作成功', content: '解冻成功', duration: 1.5 });
                    this.refreshHouseInfo();
                } else {
                    MModal.success({ title: '操作失败', content: result.info });
                }
            },
            onCancel() {}
        });
    };
    render() {
        const { visible, onClose, itemInfo } = this.props;
        const { detailModalVisible, ownerVisible, cashBookVisible,
            unfreezeDepositVisible, unfreezeRentVisible, houseInfo, houseEditModalVisible } = this.state;
        const { closeDetailModal, showDetailModal,
            closeOwnerModal, showOwnerModal,
            deleteHouseConfirm, showCashBookModal,
            closeCashBookModal, closeUnfreezeDepositModal,
            showUnfreezeDepositModal, showUnfreezeRentModal,
            closeUnfreezeRentModal, showHouseEditModal, closeHouseEditModal,
            frozenLock, unFrozenLock } = this;

        const address = `${itemInfo.address_detail}`;
        const { contract_info, renter_info, owner_info } = houseInfo;

        const hideStyle = { visibility: 'hidden' };

        //分期合同是否可以解冻
        let can_freeze = false;
        if (contract_info && contract_info.contract_type == '分期合同') {
            if (contract_info.end_time < moment().unix() || contract_info.contract_status == 1) can_freeze = true;
        }

        return (
            <MModal visible={visible} onClose={onClose} width={1020} height={helper.fixHeight(660)}>
                <Spin tip="loading" spinning={this.state.spinning} delay={150}>
                    <div className={houseModeStyle['house-info-modal']}>
                        <div className={houseModeStyle['house-info-head']}>
                            <div className={houseModeStyle['house-name']} title={address}>{address}</div>
                            {contract_info ?
                                <div className={houseModeStyle['house-profit']}>
                                    {(!isNaN(contract_info.profit) && contract_info.profit < 0) ?
                                        <i className={houseModeStyle['head-icon-deficit']}>亏损</i> :
                                        <i className={houseModeStyle['head-icon']}>利润</i>}
                                    <span title={isNaN(contract_info.profit) ? contract_info.profit : contract_info.profit / 100 + '元'}>
                                        {isNaN(contract_info.profit) ? contract_info.profit : contract_info.profit / 100 + '元'}</span>
                                </div> :
                                <div className={houseModeStyle['house-profit']} style={hideStyle}>
                                    <i className={houseModeStyle['head-icon']}>利润</i>
                                </div>
                            }
                            {contract_info &&
                            <div className={houseModeStyle['house-state']}>
                                {contract_info.contract_type == '分期合同' ?
                                    <i className={houseModeStyle['head-icon']} style={{ backgroundColor: '#ffbd48' }}>分期</i> :
                                    <i className={houseModeStyle['head-icon']} style={{ backgroundColor: '#ffbd48', ...hideStyle }} />}
                                {houseInfo.lock ?
                                    (houseInfo.lock_frozen ?
                                        <span className={houseModeStyle['state-lock']} onClick={unFrozenLock}><img src="/static/alliance2/image/house/info-lock.png" /></span> :
                                        <span className={houseModeStyle['state-lock']} onClick={frozenLock}><img src="/static/alliance2/image/house/info-lock-open.png" /></span> ) :
                                    <span className={houseModeStyle['state-lock']} style={hideStyle}><img src="/static/alliance2/image/house/info-lock.png" /></span>}
                                {contract_info.overdue_day > 0 ?
                                    <div className={houseModeStyle['state-type']}><div className={houseModeStyle['state-type-icon']}>逾</div>{contract_info.overdue_day}天</div> :
                                    <div className={houseModeStyle['state-type']} style={hideStyle}><div className={houseModeStyle['state-type-icon']}>逾</div>0天</div>
                                }
                                {contract_info.contract_type !== '分期合同' && contract_info.contract_status == 1 &&
                                <span className={houseModeStyle['state-text-btn']}>已终止</span>}
                                {contract_info.contract_type == '分期合同' && contract_info.contract_status == 1 && contract_info.stage_will_pay === false &&
                                <span className={houseModeStyle['state-text-btn']}>已终止</span>}
                                {contract_info.contract_status == 0 &&
                                <a className={houseModeStyle['state-text-btn']} href="javascript:void(0);" onClick={this.terminateContractConfirm}>终止合同</a>}
                                {(contract_info.contract_type == '分期合同' && contract_info.contract_status == 1 && contract_info.stage_will_pay) &&
                                <a className={houseModeStyle['state-text-btn']}  href="javascript:void(0);" onClick={() => this.payStageContract(contract_info.stage_will_pay)}>已终止去支付</a>}
                            </div>}

                        </div>
                        <div className={houseModeStyle['house-rent-info']}>
                            {!renter_info ?
                                <div className={houseModeStyle['rent-info-column']}>
                                    <div className={houseModeStyle['rent-info-item']}><span>租客信息暂无</span></div>
                                </div> :
                                <div className={houseModeStyle['rent-info-column']}>
                                    <div className={houseModeStyle['rent-info-item']}><span>租客：</span>{renter_info.renter_name}</div>
                                    <div className={houseModeStyle['rent-info-item']}><span>租金：</span>{renter_info.rent / 100}元</div>
                                    <div className={houseModeStyle['rent-info-item']}><span>租期：</span>{renter_info.rent_time}</div>
                                    <div className={houseModeStyle['rent-info-item']}><span>电话：</span>{renter_info.mobile}</div>
                                    <div className={houseModeStyle['rent-info-item']}><span>付款：</span>{renter_info.pay_type}</div>
                                </div>
                            }
                            {!owner_info ?
                                <div className={houseModeStyle['rent-info-column']}>
                                    <div className={houseModeStyle['rent-info-item']}><span>房东信息暂无</span></div>
                                </div> :
                                <div className={houseModeStyle['rent-info-column']}>
                                    <div className={houseModeStyle['rent-info-item']}><span>房东：</span>{owner_info.owner}</div>
                                    <div className={houseModeStyle['rent-info-item']}><span>租金：</span>{!owner_info.rent ? '' : `${owner_info.rent}`.split('-').map(val => val / 100).join('-') + '元'}</div>
                                    <div className={houseModeStyle['rent-info-item']}><span>租期：</span>{owner_info.rent_time}</div>
                                    <div className={houseModeStyle['rent-info-item']}><span>电话：</span>{owner_info.mobile}</div>
                                    <div className={houseModeStyle['rent-info-item']}><span>付款：</span>{owner_info.pay_type}</div>
                                </div>}
                            {authCheck('房东编辑', '房源') &&
                            <a className={houseModeStyle['edit-house-owner-btn']} href="javascript:void(0);" onClick={showOwnerModal}>编辑</a>}
                            <HouseOwnerModal visible={ownerVisible} onClose={closeOwnerModal} houseInfo={houseInfo} />
                        </div>
                        <div className={houseModeStyle['house-info-more']}>
                            <a className={houseModeStyle['more-btn']} href="javascript:void(0);" onClick={showDetailModal}>房源详情</a>
                            <HouseDetailModal visible={detailModalVisible} onClose={closeDetailModal} houseInfo={houseInfo} />
                            <a className={houseModeStyle['more-btn']} href="javascript:void(0);" onClick={showHouseEditModal}>编辑房源</a>
                            {(contract_info && contract_info.contract_type == '分期合同' && !can_freeze) &&
                            <span><a className={houseModeStyle['more-btn-label']} href="javascript:void(0);" >押金冻结</a><span className={houseModeStyle['more-num']}>{contract_info.sum_deposit / 100}元</span></span>}
                            {(contract_info && contract_info.contract_type == '分期合同' && can_freeze) &&
                            <span><a className={houseModeStyle['more-btn-label']} href="javascript:void(0);" onClick={showUnfreezeDepositModal}>押金解冻</a><span className={houseModeStyle['more-num']}>{contract_info.sum_deposit / 100}元</span></span>}
                            {(contract_info && contract_info.contract_type == '分期合同' && contract_info.sum_rent == 0) &&
                            <span><a className={houseModeStyle['more-btn-label']} href="javascript:void(0);">租金冻结</a><span className={houseModeStyle['more-num']}>0元</span></span>}
                            {(contract_info && contract_info.contract_type == '分期合同' && contract_info.sum_rent > 0) &&
                            <span><a className={houseModeStyle['more-btn-label']} href="javascript:void(0);" onClick={showUnfreezeRentModal}>租金解冻</a><span className={houseModeStyle['more-num']}>{contract_info.sum_rent / 100}元</span></span>}
                            <UnfreezeDepositModal visible={unfreezeDepositVisible} onClose={closeUnfreezeDepositModal} />
                            <UnfreezeRenterModal visible={unfreezeRentVisible} onClose={closeUnfreezeRentModal} />
                            <HouseEditModal visible={houseEditModalVisible} itemInfo={itemInfo} onClose={closeHouseEditModal} />
                        </div>
                        <div className={houseModeStyle['house-info-other']}>
                            <div className={houseModeStyle['ls']}>
                                <div className={houseModeStyle['house-info-store']}>
                                    <span>{houseInfo.store_name}-{houseInfo.broker_name}</span>
                                </div>
                                <div className={houseModeStyle['house-info-profit']}>
                                    <span>总利润：{!isNaN(houseInfo.profitSum) ? houseInfo.profitSum / 100 + '元' : houseInfo.profitSum}</span>
                                </div>
                                {houseInfo.can_delete &&
                                <a className={houseModeStyle['delete-btn']} title="放入回收站" onClick={deleteHouseConfirm} />}
                            </div>
                            {authCheck('记账本', '房源') &&
                            <div className={houseModeStyle['tool-calc']} title="记账本" onClick={showCashBookModal}>
                                <span>记账本</span>
                                <img src="/static/alliance2/image/house/jisuanqi.png" />
                            </div>}
                            <CashBookModal visible={cashBookVisible} onClose={closeCashBookModal} houseInfo={houseInfo} />
                        </div>
                    </div>
                </Spin>
            </MModal>
        );
    }
}

export default HouseInfoModal;